package com.huluobo.user.view

import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.HttpType
import com.huluobo.lib_base.RoutePath
import com.huluobo.lib_base.UIState
import com.huluobo.lib_base.entity.User
import com.huluobo.lib_http.Const
import com.huluobo.user.UserIntent
import com.huluobo.user.UserViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/3/17.
 */

@Composable
fun LoginPage(navHostController: NavHostController, vm: UserViewModel = hiltViewModel()) {
    var username by remember {
        mutableStateOf("")
    }

    var password by remember {
        mutableStateOf("")
    }

    var role by remember {
        mutableStateOf("员工")
    }
    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        ToastUtils.showLong("登录失败:${it.msg}")
                        Log.e("TagA", "登陆失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        val mmkv = MMKV.defaultMMKV()
                        mmkv.encode(Const.PARAM_LOGIN_USERNAME, username)
                        mmkv.encode(Const.PARAM_LOGIN_PASSWORD, password)
                        mmkv.encode(Const.PARAM_LOGIN_ROLE, role)
                        mmkv.encode(Const.PARAM_TOKEN, it.data.toString())
                        ToastUtils.showLong("欢迎回来:$username")
                        navHostController.popBackStack()
                    }
                }
            }
        }
    })

    Column(
        verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier
            .padding(20.dp)
            .fillMaxWidth()
    ) {
        BaseTitle(navHostController = navHostController, title = "登录")
        Spacer(modifier = Modifier.height(100.dp))
        OutlinedTextField(value = username, onValueChange = { username = it }, Modifier.fillMaxWidth(), label = {
            Text(text = "用户名")
        }, leadingIcon = { Icon(imageVector = Icons.Default.AccountCircle, contentDescription = "") })
        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            Modifier.fillMaxWidth(),
            label = {
                Text(text = "密码")
            },
            leadingIcon = { Icon(imageVector = Icons.Default.AccountCircle, contentDescription = "") },
            visualTransformation = PasswordVisualTransformation()
        )
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(text = "角色 : ")
            Checkbox(checked = role == "经理", onCheckedChange = {
                if (it) {
                    role = "经理"
                }
            })
            Text(text = "经理")
            Checkbox(checked = role == "员工", onCheckedChange = {
                if (it) {
                    role = "员工"
                }
            })
            Text(text = "员工")
        }

        Text(text = "用户注册", modifier = Modifier.clickable {
            navHostController.navigate(RoutePath.ADD_EMPLOYEE)
        })

        Button(onClick = {
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                ToastUtils.showLong("输入项不能为空")
                return@Button
            }

            if (!username.matches(Regex("[A-z0-9]{3,10}"))) {
                ToastUtils.showLong("用户名不匹配,需要字母或者数字,3到10位")
                return@Button
            }

//            vm.sendIntent(UserIntent.Login(username, password, if (role == "经理") 1 else 2))
            val map = mapOf(
                Const.PARAM_U_NAME to username,
                Const.PARAM_U_PASSWORD to password
            )
            vm.sendIntent(UserIntent.LoginNetwork(map))
        }) {
            Text(text = "登录")
        }
    }
}